import { COS_HOST, httpServer } from "../../utils/httpServer";

// pages/activity-sign-up/activity-sign-up.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    COS_HOST,

    actId: 0,
    session_id: 0,
    session: {}, // 场次信息
    thumb: '',
    price: 0,
    fields: [],
    sessions: [],
    formData: {},
    phone: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      actId: options.id
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      phone: wx.getStorageSync('phone')
    })
    wx.showLoading({
      mask: true,
      title: '加载中',
    });

    httpServer('POST', 'Home', 'GetActCustomField', {
      id: this.data.actId
    }).then(res => {
      if (res.result == 'success') {
        this.setData({
          thumb: res.info.thumb,
          price: res.info.price,
          sessions: res.info.session,
          session_id: res.info.session[0].session_id,
          session: res.info.session[0],
          fields: res.info.fields,
        })
      } else {
        wx.showToast({
          icon: 'none',
          title: res.info,
        });
      }
    }).catch(err => {
      console.error(err);
    }).finally(() => {
      wx.hideLoading();
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 误操作添加之后是否需要删除操作
  handleAddTap() {
    const list = this.data.personList;
    list.push({
      group_id: Date.now(),
    });
    this.setData({
      personList: list,
    });
  },
  handleInputChange(e) {
    const { value } = e.detail;
    const { index, key } = e.currentTarget.dataset;
    this.setData({
      [`formData.${key}`]: value,
    });
  },
  handleSessionChange(e) {
    const { value } = e.detail;
    this.setData({
      session: this.data.sessions[value],
    })
  },
  handlePickerChange(e) {
    console.log(e);
    const { value } = e.detail;
    const { key, sel } = e.currentTarget.dataset;
    this.setData({
      [`formData.${key}`]: sel[value],
    })
  },
  handleRangeChange(e) {
    const { value } = e.detail;
    this.setData({
      session_id: value,
    });
  },
  handleSubmitTap() {
    // 检查是否有字段未填
    // 同时将数据结构拼好
    let flag = false;
    const content = [];

    // for (let key in this.data.formData) {
    //   content.push(key)
    //   content.push(this.data.formData[key])
    // }
    
    const keys = Object.keys(this.data.formData);
    for (const i in this.data.fields) {
      const field = this.data.fields[i]
      content.push(field.content)
      if (keys.indexOf(field.content) !== -1) {
        content.push(this.data.formData[field.content]);
      } else {
        content.push('');
      }
    }

    if (flag) {
      wx.showToast({
        icon: 'error',
        title: '请填写人员信息',
      });
      return;
    }

    const args = {
      openid: wx.getStorageSync('openid'),
      id: this.data.actId,
      session_id: this.data.session.session_id,
      form: [{
        content,
      }],
    };
    console.log(args)
    httpServer('POST', 'User', 'ApplyActive', args)
      .then(res => {
        if (res.result == 'success') {
          wx.navigateTo({
            url: `/pages/success/success?price=${this.data.price}`,
          })
          // wx.showToast({
          //   icon: 'none',
          //   title: res.info,
          //   duration: 1000,
          //   complete: () => {
          //     setTimeout(() => {
          //       wx.navigateBack();
          //     }, 1000);
          //   }
          // });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.info,
          });
        }
      })
      .catch(err => {
        console.error(err);
      })
  },

  getPhoneNumber(e) {
    wx.showLoading({
      mask: true,
      title: '加载中',
    });
    const {code, errMsg, errno} = e.detail;
    if (!code) {
      wx.showToast({
        icon: 'none',
        title: '用户拒绝授权',
      })
      return;
    }
    if (errno) {
      wx.showToast({
        icon: 'none',
        title: errMsg,
      })
      return;
    }
    httpServer('POST', 'User', 'GetPhoneNumber', {code})
      .then(phoneRes => {
        if (phoneRes.result == 'success') {
          const phone = phoneRes.info;
          wx.login({
            success: (loginRes) => {
              if (loginRes.code) {
                wx.request({
                  url: `https://api.huacheng-xiaochengxu.com/musoundic/callback.php?code=${loginRes.code}&phone=${phone}`,
                  success: (res) => {
                    if (res.data.result == 'success') {
                      const {openid, phone} = res.data.info;
                      wx.setStorageSync('openid', openid);
                      wx.setStorageSync('phone', phone);
                      this.setData({
                        phone,
                      })
                      this.genUser(openid, phone, -1, -1);
                    }
                  },
                  fail(res) {
                    console.error('error : ', res);
                  },
                  complete() {
                    wx.hideLoading();
                  }
                });
              } else {
                wx.showToast({
                  icon: 'none',
                  title: res.errMsg,
                })
              }
            },
          })
        } else {
          wx.hideLoading({
            complete:() => {
              wx.showToast({
                icon: 'none',
                title: phoneRes.info,
              })
            }
          })
        }
      })
      .catch(err => {
        console.error(err);
        wx.hideLoading();
      })
  },

  genUser(openid, phone, avatar, nickname) {
    httpServer('POST', 'User', 'SaveUser', {
      openid,
      phone,
      avatar,
      nickname,
    }).then(res => {
      if (res.result == 'success') {
        wx.setStorage({
          key: 'openid',
          data: openid,
          success:() => {
            httpServer('POST', 'User', 'GetInfo', {openid}).then(res => {
              wx.hideLoading();
              if (res.result == 'success') {
                let info = {};
                Object.assign(info, res.info, {isLogin: true});
                getApp().globalData.userInfo = info;
                this.setData({
                  userInfo: info,
                  openid,
                });
              } else {
                console.error('set-user-info getinfo error : ', res.info);
                wx.showToast({
                  icon: 'none',
                  title: res.info,
                })
              }
            }).catch(err => {
              console.error(err);
              wx.hideLoading();
            })
          }
        });
      } else {
        wx.hideLoading({
          success: () => {
            wx.showToast({
              icon: 'none',
              title: res.info,
            });
          }
        });
      }
    }).catch(err => {
      console.error(err);
    });
  },

  handleRemoveTap(e) {
    const { index } = e.currentTarget.dataset;
    let { personList } = this.data;
    if (personList.length == 1) {
      wx.showToast({
        icon: 'none',
        title: '至少要有一个人报名',
      });
      return;
    }

    personList.splice(index, 1);

    this.setData({
      personList,
    });
  },
})